<?php

use think\Cache;

if (!function_exists('knowbase_handle_url_protocol')) {
   
    function knowbase_handle_url_protocol($url) {
        if (($pos = strpos($url,"://"))!==false){
            $url = substr($url, $pos+1);
        }
        return $url;
    }
}

if (!function_exists('knowbase_page_addon_url')) {
    /**
     * 返回伪静态的插件文档URL地址
     * @param $project 项目
     * @param $page    页面
     */
    function knowbase_page_addon_url($project, $page)
    {
        $config       = get_addon_config('knowbase');
        if ($project['identify']) {
            $url =  addon_url('knowbase/index/rewrite_document', [':name' => $project['identify'], ':id' => $page['identify'] ?: $page['id']],true,true);
        } else {
            $url =  addon_url('knowbase/index/document', [':id' => $page['id']],true,true);
        }
       
       
        if (config('url_domain_deploy') && $config['domain']) {
            $sub_domain = preg_replace('/^(\w+?)\./',$config['domain'].'.', $_SERVER['HTTP_HOST']);
            if ($sub_domain!=$_SERVER['HTTP_HOST']) {
                $url = preg_replace('/^(https?:\/\/)[^\/]+/', '${1}' . $_SERVER['HTTP_HOST'], $url);
            }
        }
        return knowbase_handle_url_protocol($url);
    }
}

if (!function_exists('knowbase_allow_create_project')) {
    /** 是否允许创建知识库项目
     * @param $member  用户信息
     * @return bool  true 允许 false 不允许
     */
    function knowbase_allow_create_project($member)
    {
       
        $authCount = \app\common\model\bdpan\Auth::where(['admin_id' => $member['id']])->count();
       
        if (KNOW_BASE_VERSION == 0 && $authCount > 0) {
            return false;
        }
        return true;
    }
}

if (!function_exists('knowbase_splitbyid')) {
    /**
     * 分裂数据中的 ID
     *
     * @param int|string|array $data
     * @param string           $field
     * @return array
     */
    function knowbase_splitbyid($data, $field = 'id')
    {
        return array_values(array_filter(knowbase_splitbyname($data, $field), 'is_numeric'));
    }
}

if (!function_exists('knowbase_splitbyname')) {
    /**
     * 分裂数据中的 NAME
     *
     * @param int|string|array $data
     * @param string           $field
     * @return array
     */
    function knowbase_splitbyname($data, $field = 'name')
    {
        if (is_int($data)) {
            $data = [$data];
        } else if (is_string($data)) {
            $data = explode(',', $data);
        } else if (is_array($data) && knowbase_array_depth($data) > 1) {
            $data = array_column($data, $field);
        } else if (is_array($data) && knowbase_is_assoc($data)) {
            $data = [$data[$field]];
        }

        return array_values(array_filter(array_unique($data), 'knowbase_is_value'));
    }
}

if (!function_exists('knowbase_array_depth')) {
    /**
     * 取得数组深度
     *
     * @param array $array
     * @return int
     */
    function knowbase_array_depth($array)
    {
        $max_depth = 1;

        foreach ($array as $value) {
            if (is_array($value)) {
                $depth = knowbase_array_depth($value) + 1;

                if ($depth > $max_depth) {
                    $max_depth = $depth;
                }
            }
        }

        return $max_depth;
    }
}

if (!function_exists('knowbase_is_assoc')) {
    /**
     * 是否为关联数组
     *
     * @param array $var
     * @return bool
     */
    function knowbase_is_assoc($var)
    {
        return is_array($var) and $var !== array_values($var) and ($keys = array_keys($var)) !== array_filter($keys, 'is_int');
    }
}

if (!function_exists('knowbase_is_value')) {
    function knowbase_is_value($var)
    {
        return $var !== '' and $var !== null;
    }
}


if (!function_exists('knowbase_groupbyid')) {
    function knowbase_groupbyid($data, $field = 'id')
    {
        $list = [];
        foreach ($data as $v) {
            $list[$v[$field]] = $v;
        }
        return $list;
    }
}

if (!function_exists('knowbase_groupsbyid')) {
    function knowbase_groupsbyid($data, $field = 'id')
    {
        $list = [];
        foreach ($data as $v) {
            $list[$v[$field]][] = $v;
        }
        return $list;
    }
}

/**
 * 关于如何将不连续的markdown标题设置成连续的方法
 * 1. 用正则获取所有的标题
 * 2. 记录所有的标题并排重
 * 3. 按照升序的方式来设置  如果 当前是 # ###  ##### 格式 匹配到#在第一个就是 1 ### 是第二个就是2 依次类推
 */
if (!function_exists('knowbase_get_title_list')) {
    function knowbase_get_title_list($content)
    {
        $list    = [];
        $matches = [];
        if (preg_match_all("/(^#.+?)\r?\n/m", $content, $matches)) {
            foreach ($matches[0] as $v) {
                $list[] = substr_count($v, '#');
            }
        }
        $list = array_values(array_unique($list));
        sort($list, SORT_STRING);
        return $list;
    }
}

if (!function_exists('knowbase_get_big_title')) {
    function knowbase_get_big_title($content)
    {
        $big = 7;
       
        $matches = [];
        if (preg_match_all("/(^#.+?)\r?\n/m", $content, $matches)) {
            foreach ($matches[0] as $v) {
                $num = substr_count($v, '#');
                if ($num < $big) {
                    $big = $num;
                }
            }
        }
        return $big;
    }
}

if (!function_exists('knowbase_title_to_code')) {
    function knowbase_title_to_code(&$content, $type = 0)
    {
       
       
        $list = knowbase_get_title_list($content);
        if (!$list) {
            return;
        }
        $data = knowbase_get_titles($content);
        foreach ($data as $title) {
            $num       = substr_count($title, '#');
            $new_title = str_replace("#", "", $title);
            $index     = 1;
            foreach ($list as $k => $v) {
                if ($v == $num) {
                    $index = $k + 1;
                    break;
                }
            }
            if ($type == 0) {
                $pre = "> ";
            } else {
                $pre = str_repeat("#", $index);
            }
            $content = str_replace($title, $pre . $new_title . "\r\n", $content);
        }
    }
}

if (!function_exists('knowbase_get_titles')) {
    function knowbase_get_titles($content)
    {
        if (preg_match_all("/(^#.+?)\r?\n/m", $content, $matches)) {
            return $matches[0];
        } else {
            return [];
        }
    }
}

if (!function_exists('knowbase_replace_content_title_level')) {
    function knowbase_replace_content_title_level($data)
    {
       
       
        $data['title'] = trim(str_replace("&nbsp;", '', $data['title']));
       
        $deep      = $data['deep'];
        $title_pre = str_repeat("#", $deep);
        if ($data['type'] == 'dir') {
            knowbase_title_to_code($data['content']);
        } else {
           
           
            knowbase_title_to_code($data['content'], 1);
            if (preg_match_all("/(^#.+?)\r?\n/m", $data['content'], $matches)) {
                for ($i = 1; $i <= 6; $i++) {
                    $sub_title_pre = str_repeat("#", $deep + $i);

                    $keywords = array_filter($matches[1], function ($v) use ($i) {
                        return substr_count($v, '#') == $i;
                    });

                   
                    if (!$keywords) {
                        break;
                    }
                    $count = 1;
                    foreach ($keywords as $k => $keyword) {
                        $sub_title = trim(str_replace(["&nbsp;", "#"], '', $keyword));
                       
                        $escaped_text = preg_quote($keyword,'/');
                        if ($i + $deep > 6) {
                            $data['content'] = preg_replace("/^{$escaped_text}/m", "<h" . ($i + $deep) . '>' . $sub_title . '</h' . ($i + $deep) . '>', $data['content'], $count);
                        } else {
                           
                            $data['content'] = preg_replace("/^{$escaped_text}/m", "{$sub_title_pre} {$sub_title}", $data['content'], $count);
                        }
                    }
                }
            }
        }
        return "{$title_pre} {$data['title']}\r\n{$data['content']}\r\n";
    }
}

if (!function_exists('knowbase_format_markdown')) {
    function knowbase_format_markdown(&$content)
    {
        $config       = get_addon_config('knowbase');
        if (preg_match_all('/<audio.+?src="(.+?)"><\/audio>/', $content, $matches)) {
            foreach ($matches[0] as $k => $v) {
                $content = str_replace($v, "[]({$matches[1][$k]} \"mp3\")", $content);
            }
        }
       
        if ($config['open_cdn'] && $config['cdn_url']) {
            if (preg_match_all('/!\[[^\]]*\]\((.+?)\)/i', $content,$matches)) {
                foreach ($matches[1] as $url) {
                   
                   
                   
                   
                    $params = parse_url($url);
                   
                    if (strpos($url, 'cdn.jsdelivr.net/gh/')!==false) {
                        $pre = $params['scheme'].'://'.$params['host'].'/gh/';
                        $temp_path = str_replace($pre, '', $url);
                        $temp_path = '/'.explode("/", $temp_path,2)[1];
                        $new_url = $config['cdn_url'].$temp_path;
                    } else {
                        if (!isset($params['path'])) {
                            continue;
                        }
                        $new_url =  $config['cdn_url'].$params['path'];
                    }
                    $content = str_replace($url, $new_url, $content);
                }
            }
        }
    }
}

if (!function_exists('knowbase_extract_substring')) {
   
    function knowbase_extract_substring($parentText, $substring)
    {
       
        $position = mb_strpos($parentText, $substring);

        $length = mb_strlen($parentText);

       
        if ($position === false) {
            if ($length > 100) {
                return mb_substr($parentText, 0, 100) . '...';
            } else {
                return $parentText;
            }
            return '';
        }

       
        $startPosition = max(0, $position - 100);

       
        $endPosition = min($length, $position + mb_strlen($substring) + 100);

       
        $extractedText = mb_substr($parentText, $startPosition, $endPosition - $startPosition);

       
        if ($startPosition > 0) {
            $extractedText = '...' . mb_substr($extractedText, 3);
        }

       
        if ($endPosition < $length) {
            $extractedText = mb_substr($extractedText, 0, -3) . '...';
        }

        return $extractedText;
    }
}

if (!function_exists('knowbase_generate_tree')) {
    /**
     * 生成树形结构  $items 数据集 has_field_son 是否给子元素分配字段 用于统计  pid 默认的父ID字段
     *
     * @param $items
     * @param $has_field_son
     * @param $pid
     * @return array
     */
    function knowbase_generate_tree($items, $has_field_son = true, $pid = 'pid')
    {
        $tree = [];
        foreach ($items as $item) {
            if (isset($items[$item[$pid]])) {
                if ($has_field_son) {
                    $items[$item[$pid]]['son'][] = &$items[$item['id']];
                } else {
                    $items[$item[$pid]][] = &$items[$item['id']];
                }
            } else {
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
}

if (!function_exists('knowbase_diy_login_url')) {
    function knowbase_diy_login_url()
    {
        $config       = get_addon_config('knowbase');
        $param = request()->param();
        if ($config['open_login_diy_url'] && $config['login_diy_url']){
            if (request()->isGet() && isset($param['s']) && strpos($param['s'], '/index/user/login')!==false && empty($param['url'])) {
                $param['s'] = str_replace("//", "/", $param['s']);
                header('Location: ' . $param['s'] . '?url=' . urlencode($config['login_diy_url']));
                exit;
            } else {
                return $config['login_diy_url'];
            }
        }
        return '';
    }
}

if (!function_exists('knowbase_show_user_navs')) {
    function knowbase_show_user_navs()
    {
        $config       = get_addon_config('knowbase');
        if ($config['show_user_navs']){
            return true;
        }
        return false;
    }
}


if (!function_exists('knowbase_get_cache')) {
    function knowbase_get_cache($key,$fn,$expire=600) {
        if (Cache::tag('knowbase')->has($key)){
            return Cache::tag('knowbase')->get($key);
        } else {
            $data = $fn();
            Cache::tag('knowbase')->set($key,$data,$expire);
            return $data;
        }
    }
}
